package com.wanglei.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wanglei.constants.SystemConstants;
import com.wanglei.domain.ResponseResult;
import com.wanglei.domain.entity.Article;
import com.wanglei.domain.entity.Category;
import com.wanglei.domain.vo.CategoryVo;
import com.wanglei.mapper.ArticleMapper;
import com.wanglei.service.CategoryService;
import com.wanglei.mapper.CategoryMapper;
import com.wanglei.utils.BeanCopyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author MrWang
* @description 针对表【sg_category(分类表)】的数据库操作Service实现
* @createDate 2023-07-01 20:53:57
*/
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
    implements CategoryService{

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public ResponseResult getCategoryList() {
        //先查哪些分类有正式文章
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<Article>()
                .eq(Article::getStatus,SystemConstants.ARTICLE_STATUS_NORMAL);
        List<Article> articles = articleMapper.selectList(queryWrapper);
        //去重
        Set<Long> categoryIds = articles.stream()
                .map(article -> article.getCategoryId())
                .collect(Collectors.toSet());


        //再根据满足条件的category_id集合进行分类列表查询 并过滤掉禁用的分类
        List<Category> categories = categoryMapper.selectBatchIds(categoryIds);
        categories.stream()
                .filter(category -> SystemConstants.STATUS_NORMAL.equals(category.getStatus()))
                .collect(Collectors.toList());

        //封装vo
        List<CategoryVo> categoryVos = BeanCopyUtils.copyBeanList(categories, CategoryVo.class);

        return ResponseResult.okResult(categoryVos);
    }
}




